﻿using System;
using System.Drawing;
using EmbeddedSharp.Core;
using EmbeddedSharp.Scripting.Interfacing.Mathematica.View;
using Zove.Runtime.Core;
using Zove.Scripting.Core.Functions;
using Zove.Runtime.Core.Zoom;

namespace EmbeddedSharp.Scripting.Interfacing.Mathematica {
    public class MmaPlotNode : FuncNode {
        public MmaPlotNode() {
            base.Value = "mmaPlot";
        }

        public override object Evaluate() {
            if (Parameters.Count < 1) {
                throw new ArgumentException(
                    "usage: mmaPlot(expr, x, from, to);");
            }

            int count = Parameters.Count;
            string result = string.Empty;

            var translator
                = new MathematicaExpressionTranslator("");
            if (Parameters[count - 1] is FormulateNode) {
                var ex = Parameters[count - 1].Evaluate() as string;
                ZoomLanguageNature languageNature = new ZoomLanguageNature();
                ExpressionParser p = languageNature.ExpressionParserFactory.CreateParser(ex);
                Node node = p.Parse();
                result = translator.Translate(node);
            } else {
                result = translator.Translate(Parameters[count - 1]);
            }

            string var = Parameters[count - 2].Value;
            string newExpr = result.Replace(var, "x");

            double from = Convert.ToDouble(Parameters[count - 3].Evaluate());
            double to = Convert.ToDouble(Parameters[count - 4].Evaluate());

            string expr = "Plot[" + newExpr + ", {x, " + from + ", " + to + "}]";
            Image image = MathematicaKernel.Instance.EvaluateToImage(expr);
            var view = new MmaGraphicView(image);

            view.Show();

            return result;
        }
    }
}